package cn.sofwin.web.blog.servlet;

import cn.sofwin.web.blog.entity.User;
import cn.sofwin.web.blog.service.UserService;
import cn.sofwin.web.blog.service.impl.UserServiceImpl;
import cn.sofwin.web.blog.utils.HttpHelper;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/blog/user/register")
public class RegisterServlet extends HttpServlet {
    UserService userService= UserServiceImpl.getInstance();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 转发到注册页面
        req.getRequestDispatcher("/register.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 处理注册请求
        HttpHelper.charset(req);
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String nickname = req.getParameter("nickname");

        if(StringUtils.isBlank(username) || StringUtils.isBlank(password)){
            HttpHelper.error("用户名或密码错误!", req, resp);
        }else{
            User user = userService.register(username, password, nickname);
            if(user == null){
                HttpHelper.error("用户名已存在！", req, resp);
            }else{
                // 重定向到登录页面
                resp.sendRedirect("/blog/user/login");
            }
        }
    }
}
